<template>
  <div>
    <div class="app-container clearfix pageHeader">
      <div class="header fl">成员分配：{{$store.getters.currentId.parentName}} - {{$store.getters.currentId.name}}</div>
      <div class="extra fr">
        <el-button @click="back">返回</el-button>
      </div>
    </div>

    <div class="margin24" style="margin-bottom: 24px;">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>已分配机构</span>
            </div>
            <div class="text item" style="height:90px;overflow:auto;">
              <el-tag :key="tag.id" v-for="tag in orgTags" closable :disable-transitions="true"
                      @close="orgTagsHandleClose(tag,'org')">
                {{tag.label}}
              </el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12" style="padding:0 5px">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>已分配用户</span>
              <!--{{currentSelection}}-->
            </div>
            <div class="text item" style="height:90px;overflow:auto;">
              <el-tag :key="tag.id" v-for="tag in userTags" closable :disable-transitions="true"
                      @close="orgTagsHandleClose(tag,'user')">
                {{tag.name}}
              </el-tag>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="app-container margin-content padding-content selectWrap">
      <el-container>
        <el-aside width="380px">
          <el-card>
            <div slot="header" class="clearfix">
              <div class="header fl">选择机构</div>
              <div class="extra fr">
                <el-input placeholder="请输入机构名" v-model="filterText" style="width:150px;">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-button type="primary" @click="updateRoleOrgs()">分配机构</el-button>
              </div>
            </div>

            <el-scrollbar :native="false" wrap-class="scroll-list" :class="noMarginRight">
              <el-tree :data="orgTree" ref="orgTree" show-checkbox highlight-current default-expand-all
                       node-key="id" :filter-node-method="filterNode" :expand-on-click-node="false"
                       :props="defaultProps" check-strictly
                       @current-change="orgCurrentChangeHandle" @check="checkHandle"
                       style="height: 284px;">
                <div class="custom-tree-node" slot-scope="{ node, data }">
                  <span @click="handleTreeRemove(data)">{{ node.label }}</span>
                  <span v-if="isShowTreeOperation(node)">
                    <el-button @click.stop="orgTagsHandleClose(node,'org')" type="text">移除</el-button>
                  </span>
                </div>
              </el-tree>
            </el-scrollbar>
          </el-card>
        </el-aside>
        <el-main style="margin-left: 20px; padding: 0;">
          <el-card>
            <div slot="header" class="clearfix">
              <div class="header fl">选择用户 - {{orgSelectionsName === '' ? '全部' : orgSelectionsName}}</div>
              <div class="extra fr">
                <el-input change-on-select v-model="query.loginName" style='width:150px;'
                          placeholder="请输入用户名" @keyup.native="doSearchUsers">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-button type="primary" @click="updateRoleUsers()">分配用户</el-button>
              </div>
            </div>
            <div class="clearfix">
              <el-table ref="userTable" :key='tableKey' :data="users" v-loading="loading" element-loading-text="加载中..."
                        height="400" @selection-change="selectionChangeHandle" style="width: 100%">
                <el-table-column :selectable="tableCanSelect" type="selection" width="55"></el-table-column>
                <el-table-column label="用户名" property="loginName" width="150"></el-table-column>
                <el-table-column label="姓名" property="name"></el-table-column>
                <el-table-column label="操作" width="50" fixed="right">
                  <template slot-scope="scope">
                    <el-button v-if="scope.row.disabled === true" @click="orgTagsHandleClose(scope.row,'user')"
                               type="text">移除
                    </el-button>
                  </template>
                </el-table-column>
                <!--<el-table-column label="电话" property="tel" ></el-table-column >-->
              </el-table>
              <div class="pagination-container align-right" v-show="users.length > 0">
                <el-pagination @current-change="handleCurrentChange" :current-page="query.pageNum"
                               :page-size="query.pageSize" layout="total, prev, pager, next" :total="total">
                </el-pagination>
              </div>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </div>

  </div>
</template>

<script>
  // api
  import { getOrgsAndUsers, updateRoleOrgs, updateRoleUsers } from '@/api/roles'
  import { getOrgTree } from '@/api/orgs'
  import { getUsers } from '@/api/users'
  import { orgTreesSetKeys } from '@/utils/tools'
  // components
  import Divider from '@/components/Divider'

  export default {
    name: 'members',
    components: {
      Divider
    },
    computed: {
      userTagsIds() {
        return this.userTags.map(item => {
          return item.id
        })
      },
      orgTagsIds() {
        return this.orgTags.map(item => {
          return item.id
        })
      }
    },
    data() {
      return {
        // 机构 start-----
        filterText: '',
        saveSetTimeoutSearch: null,
        noMarginRight: '',
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        defaultOrg: [
          {}
        ],
        orgTree: [],
        // 机构 end-------

        // 用户 start-----
        tableKey: 0,
        loading: false,
        users: [],
        query: {
          loginName: '',
          pageNum: 1,
          pageSize: 20
        },
        total: 0,
        // 用户 end-------
        orgSelections: '',//用于记录选择当前树节点的id，用于获取用户
        orgSelectionsName: '',//用于记录当前选中的机构树的名字
        orgSelectionsArr: [],//记录机构树选中的选项数组id数组
        // orgChecks: [],
        orgTags: [], //已经分配的用户机构tags对象数组
        userTags: [],//已经分配的用户tags对象数组
        userSelections: [], //用于记录当前分页获取选择的用户列表id数组
        userSelectionsAll: [] //记录所有选过的用户节点
      }
    },
    watch: {
      filterText(val) {
        this.$refs['orgTree'].filter(val)
      }
//      orgSelections() {
//        this.getUsers()
//      },
//      orgTags() {
//        this.setCheckedKeys()
//      }
    },
    created() {
      this.getOrgTree()
      this.$nextTick(() => {
        this.noMarginRight = 'noMarginRight'//用来抖动一下el-scroller
        setTimeout(() => {
          this.noMarginRight = ''
        }, 50)
      })
    },
    methods: {
      getOrgTree() {
        getOrgTree().then((res) => {
          // this.orgTree = [...this.defaultOrg, ...res.data.data]
          res = res.data
          this.orgTree = [{id: -1, label: '全部', name: '全部', children: res.data}]
          this.$nextTick(() => {
            this.$refs['orgTree'].setCurrentKey(-1)
            this.getUsers()
          })
        })
      },
      getCheckedNodes() {
        this.orgTags = this.$refs['orgTree'].getCheckedNodes()
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      // 当前选中节点变化时触发的事件
      orgCurrentChangeHandle(current) {
        this.query.loginName = ''
        this.query.pageNum = 1
        if (current.id === -1) {
          this.orgSelections = ''
          this.orgSelectionsName = ''
        } else {
          this.orgSelections = current.id
          this.orgSelectionsName = current.label
        }
        this.getUsers()
      },
      // 当复选框被点击的时候触发
      checkHandle(current, checked) {
        this.orgSelectionsArr = this.orgTags
        this.orgSelectionsArr = checked.checkedNodes.map(item => {
          return {
            id: item.id,
            name: item.nameZh,
            label: item.nameZh
          }
        })
      },
      /**
       * 分页方法
       * @param val
       */
      handleCurrentChange(val) {
        this.query.pageNum = val
        this.getUsers()
      },
      /**
       * 用户树触发的选择事件
       * @param val
       */
      selectionChangeHandle(val) {
        this.userSelections = val.map(item => {
          return item.id
        })
      },
      /**
       * 获取用户
       */
      getUsers() {
        this.loading = true
        const params = Object.assign({}, this.query, {orgId: this.orgSelections})
        getUsers(params).then((res) => {
          res = res.data
          this.users = []
          this.$nextTick(() => {
            setTimeout(() => {
              this.total = res.data.total
              if (res.data.dataList !== null && res.data.dataList !== '') {
                this.users = res.data.dataList //显示用户列表
                this.getOrgsAndUsers()
              }
              this.loading = false
            }, 100)
          })
        })
      },
      getOrgsAndUsers() {
        getOrgsAndUsers({id: this.$store.getters.currentId.id}).then((res) => {
          res = res.data
//          this.users = res.data.users
          this.userTags = res.data.users.map(item => {
            return {name: item.loginName, id: item.id}
          })
          this.orgTags = res.data.orgs.map(item => {
            return {
              id: item.id,
              label: item.nameZh
            }
          })
          const orgsKeys = res.data.orgs.map(item => {
            return item.id
          })
          if (this.orgTags.length > 0) {
            const __orgTreeRefs = this.$refs['orgTree']
            this.orgTags.forEach(item => {
              orgTreesSetKeys(this.orgTree, item) //设置不可选项目
            })
            __orgTreeRefs.setCheckedKeys(orgsKeys)//设置选中状态
          }

          //生成获取当前列表的用户id数组
          const _userIds = this.users.map(item => {
            return item.id
          })
          //定义需要选择的节点
          let selectionKey = []
          if (this.userTags.length > 0) {
            //比较获取需要在用户列表中的索引
            this.userTags.map(item => {
              if (_userIds.indexOf(item.id) > -1) {
                selectionKey.push(_userIds.indexOf(item.id))
              }
            })
          }
          //把匹配出来的id自动勾选
          this.$nextTick(() => {
            selectionKey.forEach(item => {
              this.$refs['userTable'].toggleRowSelection(this.users[item])
            })
          })
        })
      },
      /**
       * 更新机构
       * **/
      updateRoleOrgs() {
        const ids = this.orgSelectionsArr.map((item) => {
          if (item.id !== -1) {
            return item.id
          }
        })
        const params = {
          id: this.$store.getters.currentId.id,
          orgIds: ids.join(',')
        }
        if (ids.join(',') === '') {
          this.$message({
            message: '至少选择一个选项',
            type: 'warning'
          })
        } else {
          updateRoleOrgs(params).then(() => {
            this.$message({message: '操作成功', type: 'success'})
            this.$refs['orgTree'].setCheckedKeys([]);
            this.getOrgsAndUsers()
          })
        }

      },
      /**
       * 更新用户
       * **/
      updateRoleUsers() {
        this.getCheckedNodes()
        if (this.userSelections.length > 0) {
          let _userTagsIds = []
          if (this.userTags.length > 0) {
            _userTagsIds = this.userTagsIds
          }
          const mergeArr = [...new Set([...this.userSelections, ..._userTagsIds])]
          const params = {
            id: this.$store.getters.currentId.id,
            userIds: mergeArr.join(',')
          }
          updateRoleUsers(params).then(() => {
            this.$message({message: '操作成功', type: 'success'})
            this.getUsers()
          })
        } else {
          this.$message({
            message: '至少选择一个选项',
            type: 'warning'
          })
        }
      },
      /**
       * 移除已分配用户触发的方法
       * */
      orgTagsHandleClose(tag, type) {
        let _name = ''
        if (type === 'user') {
          if (Object.keys(tag).length > 3) {
            tag = this.userTags[this.userTagsIds.indexOf(tag.id)]
          }
          _name = '[' + tag.name + ']' + ' 用户'
        } else {

          if (Object.keys(tag).length > 3) {
            tag = this.orgTags[this.orgTagsIds.indexOf(tag.data.id)]
          }
          console.log(tag)
          _name = '[' + tag.label + ']' + ' 机构'
        }
        this.$confirm(`确定移除${_name}吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _ids = ''
          if (type === 'user') {
            let _spliceArr = this.userTags
            _spliceArr.splice(_spliceArr.indexOf(tag), 1)
            _spliceArr = _spliceArr.map(item => {
              return item.id
            })
            _ids = _spliceArr
            const params = {
              id: this.$store.getters.currentId.id,
              userIds: _ids.join(',')
            }
            updateRoleUsers(params).then(res => {
              this.$message({message: '操作成功', type: 'success'})
              this.getUsers()
            })
          } else {
            let _spliceArr = this.orgTags
            _spliceArr.splice(_spliceArr.indexOf(tag), 1)
            _spliceArr = _spliceArr.map(item => {
              return item.id
            })
            _ids = _spliceArr
            const params = {
              id: this.$store.getters.currentId.id,
              orgIds: _ids.join(',')
            }
            updateRoleOrgs(params).then(() => {
              this.$message({message: '操作成功', type: 'success'})
              this.$refs['orgTree'].setCheckedKeys([]);
              this.getOrgTree()
            })
          }
        }).catch(() => {
        })
      },
      back() {
        this.$parent.back()
      },

      /**
       * 表格不可选
       * @param row
       * @returns {boolean}
       */
      tableCanSelect(row) {
        if (this.userTagsIds.indexOf(row.id) > -1) {
          row.disabled = true
          return false
        } else {
          return true
        }
      },
      handleTreeRemove(node) {
        console.log(node)
      },
      /**
       * 判断是否显示机构移除按钮
       * @param node
       * @returns {boolean}
       */
      isShowTreeOperation(node) {
        const _idsArr = this.orgTagsIds
        if (_idsArr.indexOf(node.data.id) > -1) {
          return true
        } else {
          return false
        }
      },
      doSearchUsers() {
        clearTimeout(this.saveSetTimeoutSearch)
        this.saveSetTimeoutSearch = setTimeout(() => {
          this.query.pageNum = 1
          this.getUsers()
        }, 500)
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-tag {
    margin-right: 10px;
  }

  .noMarginRight {
    .el-scrollbar__wrap {
      margin-right: -16px !important;
    }
  }

  .el-card__header {
    padding: 10px;
    .header {
      padding: 2px 0;
    }
    .extra {
      padding: 0 !important;
    }
  }

  .el-card__body {
    padding: 10px;
  }

  .selectWrap {
    .el-card__body {
      height: 489px;
    }
  }

  .el-tag {
    margin: 5px;
  }

  .el-tree {
    height: 470px !important;
  }

  .alreadyGrant {
    margin-bottom: 10px !important;
  }

  .el-table {
    .el-button--mini {
      padding: 0;
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
